package com.sita.bike.utils;

import com.sita.bike.beans.PersonBean;
import com.sita.bike.persistence.Credential;
import com.sita.bike.persistence.CredentialDao;
import com.sita.bike.persistence.GroupChatDetailEvent;
import com.sita.bike.persistence.GroupChatDetailEventDao;
import com.sita.bike.persistence.GroupMember;
import com.sita.bike.persistence.GroupMemberDao;
import com.sita.bike.persistence.Person;
import com.sita.bike.persistence.PersonDao;
import com.sita.bike.persistence.Route;
import com.sita.bike.persistence.RouteDao;
import com.sita.bike.persistence.RouteData;
import com.sita.bike.persistence.RouteDataDao;
import com.sita.bike.persistence.RtBlacklistEntity;
import com.sita.bike.persistence.RtBlacklistEntityDao;
import com.sita.bike.persistence.RtResourceEntityDao;
import com.sita.bike.persistence.TrendMember;
import com.sita.bike.persistence.TrendMemberDao;
import com.sita.bike.rest.model.Account;
import com.sita.bike.support.Constants;
import com.sita.bike.support.GlobalContext;
import com.sita.tboard.ui.tools.L;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import de.greenrobot.dao.query.QueryBuilder;

/**
 * Class PersistUtils is for
 *
 * @author xiaodong on 15/3/1.
 */
public class PersistUtils {
    public static PersonBean findPersonBean() {
        PersonBean personBean = new PersonBean();
        PersonDao personDao = GlobalContext.getDaoSession().getPersonDao();
        CredentialDao credentialDao = GlobalContext.getDaoSession().getCredentialDao();
        List<Person> persons = personDao.loadAll();
        List<Credential> credentials = new ArrayList<Credential>();
        int size = persons.size();
        if (size == 0) {
            return personBean;
        }
        if (size == 1) {
            Person person = persons.remove(0);
            QueryBuilder qb = credentialDao.queryBuilder().where(CredentialDao.Properties.PersonId.eq(person.getId()));
            credentials = qb.list();
            if (credentials.size() > 0) {
                Credential credential = credentials.remove(0);
                personBean.person = person;
                personBean.credential = credential;
            } else {
                personDao.delete(person);
            }
        }
        // clean dirty
        if (size > 1) {
            for (Person person : persons) {
                personDao.delete(person);
            }
            for (Credential credential : credentials) {
                credentialDao.delete(credential);
            }
        }
        return personBean;
    }

    public static void savePersonCredential(PersonBean personBean) {
        PersonDao personDao = GlobalContext.getDaoSession().getPersonDao();
        personDao.insertOrReplace(personBean.person);
        personBean.credential.setPerson(personBean.person);
        CredentialDao credentialDao = GlobalContext.getDaoSession().getCredentialDao();
        credentialDao.insertOrReplace(personBean.credential);
    }

    public static void updatePerson(Person person) {
        PersonDao personDao = GlobalContext.getDaoSession().getPersonDao();
        personDao.insertOrReplace(person);
    }

    public static void saveCredential(Credential credential) {
        CredentialDao credentialDao = GlobalContext.getDaoSession().getCredentialDao();
        credentialDao.insertOrReplace(credential);
    }

    public static void updateCredential(Credential credential) {
        CredentialDao credentialDao = GlobalContext.getDaoSession().getCredentialDao();
        credentialDao.update(credential);
    }

    public static void deleteAllCredential() {
        CredentialDao credentialDao = GlobalContext.getDaoSession().getCredentialDao();
        credentialDao.deleteAll();
    }

    public static void clearDatabase() {
        try {
            PersonDao personDao = GlobalContext.getDaoSession().getPersonDao();
            CredentialDao credentialDao = GlobalContext.getDaoSession().getCredentialDao();
            RouteDao routeDao = GlobalContext.getDaoSession().getRouteDao();
            RouteDataDao routeDataDao = GlobalContext.getDaoSession().getRouteDataDao();

            credentialDao.deleteAll();
            personDao.deleteAll();
            routeDataDao.deleteAll();
            routeDao.deleteAll();
        } catch (Exception e) {
            L.e(e);
        }
    }

    public static void deleteRouteData(long routeId) {
        RouteDataDao routeDataDao = GlobalContext.getDaoSession().getRouteDataDao();
        List<RouteData> routeDataList = getRouteDataList(routeId);
        routeDataDao.deleteInTx(routeDataList);
    }

    public static void deleteRoute(long routeId) {
        RouteDao routeDao = GlobalContext.getDaoSession().getRouteDao();
        routeDao.deleteByKey(routeId);
    }

    public static long saveRoute(Route route) {
        RouteDao routeDao = GlobalContext.getDaoSession().getRouteDao();
        long id = routeDao.insertOrReplace(route);
        route.setId(id);
        return id;
    }

    public static void updateRoute(Route route) {
        RouteDao routeDao = GlobalContext.getDaoSession().getRouteDao();
        routeDao.update(route);
    }

    public static boolean findRoute() {
        RouteDao routeDao = GlobalContext.getDaoSession().getRouteDao();
        List<Route> routes = routeDao.loadAll();
        return routes.size() != 0;
    }

    public static Route getRoute(long routeId) {
        RouteDao routeDao = GlobalContext.getDaoSession().getRouteDao();
        List<Route> routeList = routeDao.queryBuilder().where(RouteDao.Properties.Id.eq(routeId)).build().list();
        return routeList.size() > 0 ? routeList.get(0) : null;
    }

    public static Route getRouteByServerId(String routeServerId) {
        RouteDao routeDao = GlobalContext.getDaoSession().getRouteDao();
        List<Route> routeList = routeDao.queryBuilder().where(RouteDao.Properties.ServerRouteId.eq(routeServerId)).build().list();
        return routeList.size() > 0 ? routeList.get(0) : null;
    }

    public static List<Route> getRoutesNotUploaded() {
        RouteDao routeDao = GlobalContext.getDaoSession().getRouteDao();
        List<Route> routeList = routeDao.queryBuilder().where(RouteDao.Properties.SyncStatus.eq(Constants.ROUTE_FILE_SYNC_STATUS_UPLOAD_NOT)).build().list();
        return routeList;
    }

    public static List<Route> getAllRoutes() {
        RouteDao routeDao = GlobalContext.getDaoSession().getRouteDao();
        return routeDao.loadAll();
    }

    public static List<Route> getTimeSelectRoutes(long start, long end) {
        RouteDao routeDao = GlobalContext.getDaoSession().getRouteDao();
        List<Route> routeList = routeDao.queryBuilder().where(RouteDao.Properties.StartTime.ge(start), RouteDao.Properties.StartTime.lt(end)).build().list();
        return routeList;
    }

    public static List<RouteData> getRouteDataList(long routeId) {
        RouteDataDao routeDataDao = GlobalContext.getDaoSession().getRouteDataDao();
        List<RouteData> routeDataList = routeDataDao.queryBuilder().where(RouteDataDao.Properties.RouteId.eq(routeId)).build().list();
        return routeDataList;
    }

    public static void saveRouteData(RouteData routeData) {
        RouteDataDao routeDataDao = GlobalContext.getDaoSession().getRouteDataDao();
        routeDataDao.insertOrReplace(routeData);
    }

    /**
     * 根据环信群聊ID获取服务器群聊ID
     */
    public static String getServiceGroupId(String groupId) {
        String serviceGroupId = null;
        GroupChatDetailEventDao dao = GlobalContext.getDaoSession().getGroupChatDetailEventDao();
        List<GroupChatDetailEvent> groupChatDetailEvents = dao.queryBuilder().where(GroupChatDetailEventDao.Properties.Groupid.eq(groupId)).build().list();
        Iterator<GroupChatDetailEvent> iterator = groupChatDetailEvents.iterator();
        while (iterator.hasNext()) {
            serviceGroupId = iterator.next().getTargetid();
        }
        return serviceGroupId;
    }

    /**
     * 根据服务器群聊ID获取环信群聊ID
     */
    public static String getEaseGroupId(String targetId) {
        String easeGroupId = null;
        GroupChatDetailEventDao dao = GlobalContext.getDaoSession().getGroupChatDetailEventDao();
        List<GroupChatDetailEvent> groupChatDetailEvents = dao.queryBuilder().where(GroupChatDetailEventDao.Properties.Targetid.eq(targetId)).build().list();
        Iterator<GroupChatDetailEvent> iterator = groupChatDetailEvents.iterator();
        while (iterator.hasNext()) {
            easeGroupId = iterator.next().getGroupid();
        }
        return easeGroupId;
    }

    /**
     * 根据服务器群聊ID判断本地是否存在群信息
     */
    public static boolean containEaseGroupId(String targetId) {
        GroupChatDetailEventDao dao = GlobalContext.getDaoSession().getGroupChatDetailEventDao();
        List<GroupChatDetailEvent> groupChatDetailEvents = dao.queryBuilder().where(GroupChatDetailEventDao.Properties.Groupid.eq(targetId)).build().list();
        if (groupChatDetailEvents.size() != 0) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 根据member的ID获取单个的GroupMember
     */
    public static GroupMember getGroupMember(String mImid) {
        GroupMember groupMember = null;
        GroupMemberDao dao = GlobalContext.getDaoSession().getGroupMemberDao();
        List<GroupMember> groupMembers = dao.queryBuilder().where(GroupMemberDao.Properties.Id.eq(mImid)).build().list();
        Iterator<GroupMember> iterator = groupMembers.iterator();
        while (iterator.hasNext()) {
            groupMember = iterator.next();
        }
        return groupMember;
    }

    public static void saveGroupMember(Account member) {
        GroupMember groupMember = new GroupMember();
        groupMember.setId(Long.parseLong(member.mAccountId));
        groupMember.setAvatarUrl(member.mAvatar);
        groupMember.setNickname(member.mNickName);
        groupMember.setGender(String.valueOf(member.mGender));
        GroupMemberDao groupMemberDao = GlobalContext.getDaoSession().getGroupMemberDao();
        groupMemberDao.insertOrReplace(groupMember);
    }

    /**
     * 根据TrendMember的ID获取单个的TrendMember
     */
    public static TrendMember getTrendMember(String accountId) {
        TrendMember trendMember = null;
        TrendMemberDao dao = GlobalContext.getDaoSession().getTrendMemberDao();
        List<TrendMember> trendMemberList = dao.queryBuilder().where(TrendMemberDao.Properties.Id.eq(accountId)).build().list();
        Iterator<TrendMember> iterator = trendMemberList.iterator();
        while (iterator.hasNext()) {
            trendMember = iterator.next();
        }
        return trendMember;
    }

    public static void saveTrendMember(Account account) {
        TrendMember trendMember = new TrendMember();
        trendMember.setId(Long.parseLong(account.mAccountId));
        trendMember.setAvatarUrl(account.mAvatar);
        trendMember.setNickname(account.mNickName);
        trendMember.setGender(String.valueOf(account.mGender));
        TrendMemberDao trendMemberDao = GlobalContext.getDaoSession().getTrendMemberDao();
        trendMemberDao.insertOrReplace(trendMember);
    }

    public static boolean hasTrendMember(String accountId) {
        TrendMemberDao dao = GlobalContext.getDaoSession().getTrendMemberDao();
        List<TrendMember> trendMemberList = dao.queryBuilder().where(TrendMemberDao.Properties.Id.eq(accountId)).build().list();
        if (trendMemberList.size() != 0) {
            return true;
        } else {
            return false;
        }
    }

    public static void deleteRtResource(String resourceId){
        RtResourceEntityDao resourceDao = GlobalContext.getDaoSession().getRtResourceEntityDao();
        resourceDao.deleteByKey(Long.valueOf(resourceId));
    }

    public static void saveRtBlacklist(List<RtBlacklistEntity> entities){
        RtBlacklistEntityDao entityDao = GlobalContext.getDaoSession().getRtBlacklistEntityDao();
        entityDao.insertOrReplaceInTx(entities);
    }


}